package com.bnd.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bnd.common.ErrorCode;
import com.bnd.domain.CharacterInfo;
import com.bnd.domain.ChatHistory;
import com.bnd.domain.vo.ChatHistoryVO;
import com.bnd.mapper.CharacterInfoMapper;
import com.bnd.service.ChatHistoryService;
import com.bnd.mapper.ChatHistoryMapper;
import com.bnd.utils.ThrowUtils;
import jakarta.annotation.Resource;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 聊天历史服务实现类
 * @author 20668
 * @description 针对表【chat_history】的数据库操作Service实现
 * @createDate 2025-09-22 22:12:28
 */
@Service
public class ChatHistoryServiceImpl extends ServiceImpl<ChatHistoryMapper, ChatHistory>
    implements ChatHistoryService{
    @Resource
    private ChatHistoryMapper chatHistoryMapper;
    @Resource
    private CharacterInfoMapper characterInfoMapper;

    /**
     * 批量保存聊天历史记录
     * @param chatId 聊天会话ID
     * @param characterId 角色ID
     * @param messageList 消息列表
     */
    @Override
    public void batchSaveChatHistory(String chatId, Long characterId, List<Message> messageList){
        //1. 参数校验
        ThrowUtils.throwIf(StrUtil.isBlank(chatId), ErrorCode.SYSTEM_ERROR, "获取chatId失败！");
        if (CollectionUtil.isEmpty(messageList)){
            return;
        }

        //2. 映射
        List<ChatHistory> chatHistoryList = messageList.stream()
                .map(message -> {
                    ChatHistory chatHistory = new ChatHistory();
                    chatHistory.setChatId(chatId);
                    chatHistory.setContent(message.getContent());
                    chatHistory.setCharacterId(characterId);
                    if (Role.USER.getValue().equals(message.getRole())) {
                        chatHistory.setRole("0");
                    } else if (Role.SYSTEM.getValue().equals(message.getRole())) {
                        chatHistory.setRole("2");
                    } else {
                        //助手
                        chatHistory.setRole("1");
                    }
                    return chatHistory;
                })
                .toList();
        chatHistoryMapper.insert(chatHistoryList);
        
        // 清除相关缓存
        clearChatHistoryCache(characterId);
        clearAllChatHistoryCache();
    }

    /**
     * 根据角色ID查询聊天历史记录（带缓存）
     * @param characterId 角色ID
     * @return 聊天历史记录列表
     */
    @Override
    //@Cacheable(value = "chatHistory", key = "#characterId", unless = "#result == null || #result.isEmpty()")
    public List<ChatHistory> listByCharacterId(Long characterId){
        ThrowUtils.throwIf(characterId == null || characterId <= 0, ErrorCode.SYSTEM_ERROR, "参数错误！");
        List<ChatHistory> resultList  = new ArrayList<>();

        //1. 将角色的打招呼语作为第一句话
        CharacterInfo characterInfo = characterInfoMapper.selectById(characterId);
        ThrowUtils.throwIf(characterInfo == null, ErrorCode.NOT_FOUND_ERROR, "角色不存在！");
        String greeting = characterInfo.getGreeting();
        ThrowUtils.throwIf(StrUtil.isBlank(greeting), ErrorCode.NOT_FOUND_ERROR, "角色打招呼语不存在！");
        ChatHistory roleChat = new ChatHistory();
        roleChat.setContent(greeting);
        roleChat.setRole("1");
        roleChat.setId(-1L);
        roleChat.setIsDel(0);

        //2. 添加角色对话历史记录
        List<ChatHistory> chatHistoryList = chatHistoryMapper
                .selectList(new LambdaQueryWrapper<ChatHistory>()
                        .eq(ChatHistory::getCharacterId, characterId)
                        //排除系统提示词
                        .ne(ChatHistory::getRole, "2")
                        .orderByAsc(characterInfo.getCreateTime() != null, ChatHistory::getCreateTime));
        if (CollectionUtil.isNotEmpty(chatHistoryList)){
            roleChat.setCreateTime(chatHistoryList.get(0).getCreateTime());
            roleChat.setUpdateTime(chatHistoryList.get(0).getUpdateTime());
            roleChat.setChatId(chatHistoryList.get(0).getChatId());
        }else {
            Date date = new Date();
            roleChat.setCreateTime(date);
            roleChat.setUpdateTime(date);
            roleChat.setChatId("");
        }
        roleChat.setCharacterId(characterId);
        resultList.add(roleChat);
        resultList.addAll(chatHistoryList);

        return resultList;
    }


    /**
     * 根据角色ID删除聊天历史记录
     * @param characterId 角色ID
     */
    @Override
    public void removeByCharacterId(Long characterId){
        ThrowUtils.throwIf(characterId == null || characterId <= 0, ErrorCode.SYSTEM_ERROR, "参数错误！");
        chatHistoryMapper.delete(new LambdaQueryWrapper<ChatHistory>().eq(ChatHistory::getCharacterId, characterId));
        
        // 清除相关缓存
        clearChatHistoryCache(characterId);
        clearAllChatHistoryCache();
    }

    /**
     * 获取每个角色的第一条聊天记录（带缓存）
     * @param keyword 关键词
     * @return 角色列表
     */
    @Override
    //@Cacheable(value = "chatHistoryFirst", key = "#keyword", unless = "#result == null || #result.isEmpty()")
    public List<ChatHistoryVO> selectFirstChatByCharacter(String keyword) {
        // 1. 获取每个角色的第一条用户聊天记录
        List<ChatHistoryVO> firstChatList = chatHistoryMapper.selectFirstChatByCharacter(keyword);
        if (CollectionUtil.isEmpty(firstChatList)){
            return Collections.emptyList();
        }
        return firstChatList;
    }

    /**
     * 清除聊天历史缓存
     * @param characterId 角色ID
     */
    //@CacheEvict(value = "chatHistory", key = "#characterId")
    @Override
    public void clearChatHistoryCache(Long characterId) {
        // 日志记录
    }

    /**
     * 清除所有聊天历史相关缓存
     */
    //@CacheEvict(value = {"chatHistory", "chatHistoryFirst"}, allEntries = true)
    public void clearAllChatHistoryCache() {
        // 日志记录
    }

}




